Writing Python objects as JSON into a file

Overview:

  • Any Python object can be serialized into JSON format.

 

  • The json module by default supports only serializing the basic types, which include dict, list, array, True, False and None. To serialize other python types using the json module read the article Serializing Python Objects Into JSON.

 

  • The json.dump() method is used to dump the contents of the Python object into a specified file.

Write a Python object as a JSON string into a file

How to use json.dump() method:

The keyword arguments of json.dump() offers several customizations in the serialization process. Some of them are explained here in detail.

The default implementation of json.dump() module supports serialization of only the dict, list, array, True, False and None. In case, if the Python object to be serialized is a type of class that is not one of the above types, a derived class of json.JSONDecoder has to be used. Alternately, a decoding function can be written and the name of the function can be passed as the value for the keyword argument default.

If any type that is not supported by json.dump()is to be skipped during the serialization process, then the keyword argument skipkeys can be passed a value of True. This will prevent raising of the exception TypeError.

When serializing Python objects, it is possible that some of them may have circular references. By default the value to the parameter check_circular is True.

Checking for circular references can be skipped, by passing the value False to the keyword argument check_circular.

The keyword argument indent of json.dump()can be used for pretty printing the JSON output.

 

Example:

# Example Python Program to dump a Python object into a file

import json

 

# Placeholder for index

class Index:

    pass

 

# A trivial book

class Book:

    toc     = None

    title   = None

    index   = None

   

    def __init__(self, toc, title, index):

        self.toc    = toc

        self.title  = title

        self.index  = index

 

# Provide a function to decode book objects        

def transform(object):

    if isinstance(object, Book) or isinstance(object, Index):

        return object.__dict__

    else:

        raise TypeError("Only Books and Index will be JSON serialized!")

 

# Create TOC for the book

toc = ["Chapter 1", "Chapter 2","Chapter 3","Chapter 4","Chapter 5","Chapter 6","Chapter 7",

       "Chapter 8", "Chapter 9","Chapter 10","Chapter 11","Chapter 12","Chapter 13","Chapter 14",

       "Chapter 15", "Chapter 16","Chapter 17","Chapter 18","Chapter 19","Chapter 20","Chapter 21",

       "Chapter 22", "Chapter 23","Chapter 24","Chapter 25","Chapter 26","Chapter 27"]

 

# Title of the book

title = "The Little Prince"

 

# Create a placeholder index

index = Index()

 

# Create output file for JSON

fileName    = "/test/Book_Little_Prince.json"

file        = open(fileName, "w")

 

# Create a book object

book        = Book(toc, title, index)

 

# Serialize the book instance into a JSON string and write to a file

json.dump(book,file,default=transform)

 

Output:

{"toc": ["Chapter 1", "Chapter 2", "Chapter 3", "Chapter 4", "Chapter 5", "Chapter 6", "Chapter 7", "Chapter 8", "Chapter 9", "Chapter 10", "Chapter 11", "Chapter 12", "Chapter 13", "Chapter 14", "Chapter 15", "Chapter 16", "Chapter 17", "Chapter 18", "Chapter 19", "Chapter 20", "Chapter 21", "Chapter 22", "Chapter 23", "Chapter 24", "Chapter 25", "Chapter 26", "Chapter 27"], "title": "The Little Prince", "index": {}}

 

 


Copyright 2024 © pythontic.com